<?php

namespace app\common\controller;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

use think\Db;

/**
 * 公共类
 */
class Common
{
    public function __construct()
    {
    }

    /**
     * 导出excel表
     * $data：要导出excel表的数据，接受一个二维数组
     * $name：excel表的表名
     * $head：excel表的表头，一维数组
     * $key：$data中对应表头的键的数组，一维数组
     * 备注：表头（对应列数）不能超过26；
     */
    public static function export($name = '表名', $data = [], $head = [], $keys = [])
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // $sheet->getDefaultRowD$spreadsheet->getProperties()

        $sheet->setTitle($name); //设置当前工作表标题

        //设置表头
        foreach ($head as $key => $value) {
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }

        //设置内容

        foreach ($data as $row => $item) {
            foreach ($keys as $key => $value) {
                $sheet->setCellValueByColumnAndRow($key + 1, $row + 2, $item[$value]);
            }
        }
        $writer = new Xlsx($spreadsheet);

        //合并单元格 合并后，赋值只能给A1，开始的坐标。
        // $sheet->mergeCells('A2:A3');//合并单元格
        //$sheet->mergeCellsByColumnAndRow(1,2,1,3);//使用数字单元格坐标合并单元格
        // $sheet->unmergeCellsByColumnAndRow(1,2,1,3);//使用数字单元格坐标拆分单元格

        //1.下载到服务器
        //$writer->save($name.'.xlsx');

        //2.输出到浏览器
        //header('Content-Type: application/vnd.ms-excel');//xls
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //xlsx
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');

        $writer->save('php://output');
        //删除清空：
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit;
    }

    /**
     * 生成审批流
     * $table 表名
     * $id 主键id
     */
    public static function set_check($table, $id)
    {
        $table = strtolower($table); //转小写
        $check = Db::name('check')->where('is_deleted', 0)->where('status', 1)->where('table', $table)->find();
        if ($check) {
            // $send_email = [];
            // if ($check['one_check']) {
            //     $send_email = Db::name('system_user')->whereIn('id', $check['one_check'])->column('mail');
            // } elseif ($check['two_check']) {
            //     $send_email = Db::name('system_user')->whereIn('id', $check['two_check'])->column('mail');
            // } elseif ($check['three_check']) {
            //     $send_email = Db::name('system_user')->whereIn('id', $check['three_check'])->column('mail');
            // }
            $ding_userid = '';
            if ($check['one_check']) {
                $ding_userid = Db::name('system_user')->whereIn('id', $check['one_check'])->value('ding_userid');
            } elseif ($check['two_check']) {
                $ding_userid = Db::name('system_user')->whereIn('id', $check['two_check'])->value('ding_userid');
            } elseif ($check['three_check']) {
                $ding_userid = Db::name('system_user')->whereIn('id', $check['three_check'])->value('ding_userid');
            }
            $check['one_check'] = $check['one_check'] ? explode(',', $check['one_check']) : [];
            $check['two_check'] = $check['two_check'] ? explode(',', $check['two_check']) : [];
            $check['three_check'] = $check['three_check'] ? explode(',', $check['three_check']) : [];
            $check['cc_man'] = $check['cc_man'] ? explode(',', $check['cc_man']) : [];
            $info = [];
            foreach ($check['one_check'] as $v) {
                $info[] = [
                    'table' => $table,
                    'primary_key' => $id,
                    'suid' => $v,
                    'check_id' => $check['id'],
                    'level' => 1
                ];
            }

            foreach ($check['two_check'] as $v) {
                $info[] = [
                    'table' => $table,
                    'primary_key' => $id,
                    'suid' => $v,
                    'check_id' => $check['id'],
                    'level' => 2
                ];
            }
            foreach ($check['three_check'] as $v) {
                $info[] = [
                    'table' => $table,
                    'primary_key' => $id,
                    'suid' => $v,
                    'check_id' => $check['id'],
                    'level' => 3
                ];
            }
            Db::name('system_user_check')->insertAll($info);
            //发送钉钉工作通知
            $data = [
                'userid_list' => $ding_userid,
                'msg' => [
                    'msgtype' => 'link',
                    'link' => [
                        "messageUrl"=> "http://114.55.29.146/admin.html#/home/plan/index.html?spm=m-68-78-73",
                        "picUrl"=>"@lALPDfYH05yuuJHNAUfNAUc",
                        "title"=> "赤伶社区团购平台",
                        "text"=> date('Y-m-d H:i:s').',有人提交了新的运营计划，请及时上系统进行审核!'
                    ]
                ]
            ];
            $dingApi = new DingApi();
            $dingApi->asyncsend_v2($data);
        } else {
            Db::name($table)->where('id', $id)->update(['status' => 1]);
        }
    }

    /**
     * 判断当前用户是否有审批权限
     * $table 表名
     * $data $data
     */
    public static function get_is_check($table, &$data)
    {
        $table = strtolower($table); //转小写
        foreach ($data as &$v) {
            $v['is_check'] = 0; //是否有审核权限
            $id = $v['id'];
            if ($v['status'] == 0) {
                $where = [
                    'table' => $table,
                    'primary_key' => $id,
                    'status' => 0
                ];
                $system_user_check = Db::name('system_user_check')->where($where)->order('level desc, id desc')->select();
                $one_check = [];
                $two_check = [];
                $three_check = [];
                foreach ($system_user_check as $vo) {
                    if ($vo['level'] == 1) {
                        $one_check[] = $vo;
                    } elseif ($vo['level'] == 2) {
                        $two_check[] = $vo;
                    } elseif ($vo['level'] == 3) {
                        $three_check[] = $vo;
                    }
                }
                if (count($one_check)) {
                    foreach ($one_check as $vo) {
                        if ($vo['suid'] == session('user.id')) {
                            $v['is_check'] = 1;
                        }
                    }
                } elseif (count($two_check)) {
                    foreach ($two_check as $vo) {
                        if ($vo['suid'] == session('user.id')) {
                            $v['is_check'] = 1;
                        }
                    }
                } elseif (count($three_check)) {
                    foreach ($three_check as $vo) {
                        if ($vo['suid'] == session('user.id')) {
                            $v['is_check'] = 1;
                        }
                    }
                }
            }
        }
    }

    /**
     * 审批通过
     */
    public static function check($table)
    {
        $id = request()->post('id');
        $suid = session('user.id');
        $table = strtolower($table); //转小写
        $where = [
            'table' => $table,
            'primary_key' => $id,
            'suid' => $suid
        ];
        Db::name('system_user_check')->where($where)->update(['status' => 1]);

        $where = [
            'table' => $table,
            'primary_key' => $id,
            'status' => 0
        ];
        //判断是否是最后一道审批
        if (!Db::name('system_user_check')->where($where)->count()) {
            Db::name($table)->where('id', $id)->update(['status' => 1]);
            //发邮箱给抄送人员
            $cc_man = Db::name('check')->where('is_deleted', 0)->where('status', 1)->where('table', $table)->value('cc_man');
            // $email = new Email();
            // $send_email = Db::name('system_user')->where('is_deleted', 0)->where('status', 1)->whereIn('id', $cc_man)->column('mail');
            // $send_title = '消息提醒';
            // $send_content = '<h1>有新的运营计划审核通过，请注意上系统查看</h1>';
            // $email->send($send_email, $send_title, $send_content);
            //发送钉钉工作通知
            $ding_userids = Db::name('system_user')->where('is_deleted', 0)->where('status', 1)->whereIn('id', $cc_man)->column('ding_userid');
            $data = [
                'userid_list' => implode(',', $ding_userids),
                'msg' => [
                    'msgtype' => 'link',
                    'link' => [
                        "messageUrl"=> "http://114.55.29.146/admin.html#/home/plan/index.html?spm=m-68-78-73",
                        "picUrl"=>"@lALPDeC228Aavb_NAUnNAUk",
                        "title"=> "赤伶社区团购平台",
                        "text"=> date('Y-m-d H:i:s').',有新的运营计划审核通过，请注意上系统查看!'
                    ]
                ]
            ];
            $dingApi = new DingApi();
            $dingApi->asyncsend_v2($data);
        } else {
            //发邮箱给下一个审批人
            // $email = new Email();
            // $where = [
            //     'table' => $table,
            //     'primary_key' => $id,
            //     'status' => 0
            // ];
            // $suid = Db::name('system_user_check')->where($where)->order('level desc')->value('suid');
            // $send_email = Db::name('system_user')->where('id', $suid)->column('mail');
            // $send_title = '待审核提醒';
            // $send_content = '<h1>有人提交了新的运营计划，请及时上系统进行审核</h1>';
            // $email->send($send_email, $send_title, $send_content);
            //发送钉钉工作通知
            $where = [
                'table' => $table,
                'primary_key' => $id,
                'status' => 0
            ];
            $suid = Db::name('system_user_check')->where($where)->order('level desc')->value('suid');
            $ding_userid = Db::name('system_user')->where('id', $suid)->value('ding_userid');
            $data = [
                'userid_list' => $ding_userid,
                'msg' => [
                    'msgtype' => 'link',
                    'link' => [
                        "messageUrl"=> "http://114.55.29.146/admin.html#/home/plan/index.html?spm=m-68-78-73",
                        "picUrl"=>"@lALPDfYH05yuuJHNAUfNAUc",
                        "title"=> "赤伶社区团购平台",
                        "text"=> date('Y-m-d H:i:s').',有人提交了新的运营计划，请及时上系统进行审核!'
                    ]
                ]
            ];
            $dingApi = new DingApi();
            $dingApi->asyncsend_v2($data);
        }
    }

    /**
     * 查看审批流
     */
    public static function get_check($table, $id)
    {
        //获取审批流
        $where = [
            'suc.table' => $table,
            'suc.primary_key' => $id,
        ];
        $system_user_check = Db::name('system_user_check')
            ->alias('suc')
            ->join('system_user su', 'su.id=suc.suid', 'left')
            ->where($where)
            ->field('suc.*,su.name')
            ->select();
        $data = [];
        foreach ($system_user_check as $k => $v) {
            $data[$v['level']][] = $v;
        }
        $data = array_values($data);
        //抄送人
        $cc_man = Db::name('check')->where('is_deleted', 0)->where('status', 1)->where('table', $table)->value('cc_man');
        $cc_mans = Db::name('system_user')->where('is_deleted', 0)->where('status', 1)->whereIn('id', $cc_man)->column('name');
        return [
            'data' => $data,
            'cc_mans' => $cc_mans,
        ];
    }

    //封装curl
    public static function curl($url, $data = null, $method = 'get', $https = true)
    {
        if (is_array($data)) {
            $data = json_encode($data);
        }
        $header = array('Content-Type:application/json;Charset=utf-8');//增加$header 设置 Content-Type:application/json
        $ch = curl_init(); //初始化
        curl_setopt($ch, CURLOPT_URL, $url); //访问的URL
        curl_setopt($ch, CURLOPT_HEADER, false); //设置不需要头信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只获取页面内容，但不输出

        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https请求 不验证证书 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
        }
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, true); //请求方式为post请求
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //请求数据
        }
        //设置为5秒，标识如果服务器5秒内没有响应，脚本就会断开连接
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        $result = curl_exec($ch); //执行请求
        curl_close($ch); //关闭curl，释放资源
        $result = empty($result) ? array() : json_decode($result, true);
        return $result;
    }
}
